
import store from '../store'
import messageType from "@/utils/message-type";
import { Notification } from 'element-ui';
import Vue from 'vue'
import {showConversation,modifyMessageStatus} from "@/api/conversation";
import el from "element-ui/src/locale/lang/el";


// webSocket与服务端连接的地址
const wsUrl = 'ws://localhost:9999/ljb-16/chat/'
const wssUrl = 'wss://localhost:9999/ljb-16/chat/'

// 重连状态
let lockReconnect = false;
// 最大重连数
const MAX_RECONNECTION = 5

// 重连计数
let count = 0;

let socket;

export function initialSocket(){
    if("WebSocket" in window){
      console.log("webSocket连接地址："+wsUrl)
      if(window.location.protocol === "http:"){
        socket = new WebSocket(wsUrl+store.getters.id)
      }else {
        socket = new WebSocket(wssUrl+store.getters.id)
      }
      socket.onopen = onOpen
      socket.onclose = onClose
      socket.onerror = onError
      socket.onmessage = onMessage
    }else{
      console.log("该浏览器暂不支持WebSocket")
    }
}


const onOpen = ()=> {
  console.log("与服务端建立webSocket连接成功！")
}

const onClose = ()=>{
  console.log("关闭与服务端的webSocket连接")
  reconnect()

}

const onError = err=>{
  console.log("webSocket连接出现错误：")
  console.log(err)
  reconnect()
}

// 重连
function reconnect() {
  if(lockReconnect) return
  lockReconnect = true
  setTimeout(function () {
    initialSocket()
    lockReconnect = false
  },2000)
}

const onMessage = res =>{
  console.log("webSocket服务端发送来消息："+res)
  let message = JSON.parse(res.data)
  switch (message.form) {
    case messageType.ADD_FRIEND: //添加好友请求消息
      store.commit('chat/ADD_REQUEST_MESSAGE_LIST',message)
      Notification.info({title:"消息",message:"收到请求添加好友消息！"})
      break;
    case messageType.FRIEND_INFORM: // 好友通知
      Notification.info({
        title:"消息",
        dangerouslyUseHTMLString: true,
        message:message.content})
      break
    case messageType.SAVE_FRIEND: // 保存好友
      store.commit('chat/ADD_FRIEND_LIST',message.friend)
      Notification.info({
        title:"消息",
        dangerouslyUseHTMLString: true,
        message:message.content})
      break
    case messageType.DELETE_FRIEND: // 删除好友
      if(message.senderId === store.getters.currentFriendInfo.userid){
        store.commit('chat/SET_CURRENT_FRIEND_INFO','')
        store.commit('chat/SET_FRIEND_ACTIVE','')
      }
      store.dispatch('chat/getFriendList');
      break
    case messageType.CONVERSATION_MESSAGE:{ // 聊天消息
      console.log(message)
      let conversationList = store.getters.conversationList; // 获取会话列表
      // 获取接收到消息所属的会话
      let conversation = conversationList.filter(item => item.id === message.conversationId)[0]
      // 判断是否存在该会话
      if (conversation) {
        // 如果发送过来的消息，不是当前会话中的，未读消息+1
        if (store.getters.currentConversation.id !== conversation.id) {
          Vue.set(conversation, 'unread', conversation.unread += 1)
        } else {
          modifyMessageStatus(conversation.id,true)
          // 是当前会话中的告诉消息发送方这条消息已读
          sendMessage({
            conversationId: conversation.id,
            toId: message.fromId,
            fromId: message.toId,
            form: messageType.MESSAGE_READ
          })
        }
        Vue.set(conversation, 'lastMessage', message);
        let conversationMessagesList = store.getters.conversationMessagesList;
        conversationMessagesList.forEach(item => {
          if (item.conversationId === message.conversationId) {
            item.messages.push(message)
          }
        });
      } else {
        showConversation(message.fromId).then(res => {
          let conversation = res.content.conversation;
          // 通过指定账号查询对应的会话，并对其状态进行修改，最后得到修改后的会话对象
          console.log(res)
          store.commit('chat/ADD_CONVERSATION_LIST', conversation)
        });
      }
      Notification.info({title:"消息",message:"收到一条来自 "+message.fromId+" 发送的消息！"})
      break
    }
    case messageType.MESSAGE_READ:{ // 修改消息状态
      let conversationMessage = store.getters.conversationMessagesList.filter(item=>
        item.conversationId === message.conversationId)[0]
      if(conversationMessage){
        conversationMessage.messages.forEach(item=>{
          if(item.toId === message.fromId){
            Vue.set(item,'status',true)
          }
        })
      }
      break
    }
  }
  console.log(message)
}

/**
 * 使用webSocket发送消息
 * @param message 消息
 */
export function sendMessage(message) {
  socket.send(JSON.stringify(message))
}
